//
//  GridLoginBottomView.swift
//  grid-ios-app
//
//  Created by wondertek on 2024/3/18.
//

import UIKit
import SnapKit

internal protocol GridLoginBottomViewDelegate: NSObjectProtocol {
    
    
    /// 点击选择协议
    /// - Parameters:
    ///   - view: GridLoginBottomView
    ///   - isSelectd: 是否选中
    func gridLoginBottomView(view: GridLoginBottomView, isSelectd: Bool);
    
    
    /// 点击登录
    /// - Parameter view: <#view description#>
    func gridLoginBottomViewClickLogin(view: GridLoginBottomView);

}

class GridLoginBottomView: UIView {

    internal weak var delegate: GridLoginBottomViewDelegate?

    private var isSelected: Bool = false
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    func setupUI() {
        backgroundColor = .clear
        addSubview(loginBtn)
        addSubview(agreeBtn)
        addSubview(textAgreeView)
        loginBtn.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.right.equalToSuperview().offset(-20)
            make.left.equalToSuperview().offset(20)
            make.height.equalTo(40)
        }
        
        textAgreeView.snp.makeConstraints { make in
            make.top.equalTo(loginBtn.snp.bottom).offset(30)
            make.width.greaterThanOrEqualTo(260)
            make.height.equalTo(32)
            make.centerX.equalToSuperview().offset(30)
        }
        
        agreeBtn.snp.makeConstraints { make in
            make.centerY.equalTo(textAgreeView.snp.centerY)
            make.width.equalTo(30)
            make.height.equalTo(30)
            make.right.equalTo(textAgreeView.snp.left)
        }
        
        
    }
    
    lazy var textAgreeView: UITextView = {
        
        let title = NSLocalizedString("已阅读并同意<用户协议条款>", tableName: "GridLocalizable", comment: "")
        let textView = UITextView()
        let tapTexts = ["<用户协议条款>"];
        let tapUrls = ["https://www.baidu.com/"];
        let string = NSLocalizedString("已阅读并同意<用户协议条款>", tableName: "GridLocalizable", comment: "")
        textView.setupUserAgreements(string, tapTexts: tapTexts, tapUrls: tapUrls)
        textView.delegate = self
        textView.backgroundColor = .clear
        return textView
    }()
    
    
    
    lazy var titleLabel: UILabel = {
        let label = UILabel(frame: .zero)
        label.font = Theme.Font.size(12)
        label.textColor = UIColor(hex6: 0x333333)
        label.numberOfLines = 1
        label.text = NSLocalizedString("已阅读并同意<用户协议条款>", tableName: "GridLocalizable", comment: "")
        label.textAlignment = .left
        return label
    }()
    
    lazy var loginBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .clear
        button.setTitle(NSLocalizedString("登录", tableName: "GridLocalizable", comment: ""), for: .normal)
        button.setTitleColor(UIColor(hex6: 0x404040, alpha: 1.0), for: .normal)
        button.titleLabel!.font = Theme.Font.size(20, bold: true)
        button.addTarget(self, action: #selector(onClickButton), for: .touchUpInside)
        button.backgroundColor  = UIColor(hex6: 0x1E90FF)
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 20
        return button
    }()
    
    lazy var agreeBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = UIColor.clear
        btn.setImage(UIImage(named: "selected_noar"), for: .normal)
        btn.setImage(UIImage(named: "selected_ar"), for: .selected)
        btn.isSelected = self.isSelected
        btn.setTitleColor(UIColor(hex6: 0x0e2077), for: .normal)
        btn.setTitleColor(UIColor(hex6: 0x0e2077), for: .selected)
        btn.addTarget(self, action: #selector(onClickAgreeButton), for: .touchUpInside)
        return btn
    }()
    
    @objc func onClickButton() {
        print("onClickButton")
        delegate?.gridLoginBottomViewClickLogin(view: self)
    }
    
    @objc func onClickAgreeButton() {
        print("onClickAgreeButton")
        self.agreeBtn.isSelected = !self.isSelected
        self.isSelected = !self.isSelected
        delegate?.gridLoginBottomView(view: self, isSelectd: self.isSelected)
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

extension GridLoginBottomView: UITextViewDelegate{
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        print("用户协议")
        print(URL.absoluteString)
        return true
    }
}


@objc public extension UITextView{

    /// 用户协议点击跳转配制方法
    func setupUserAgreements(_ content: String, tapTexts: [String], tapUrls: [String], tapColor: UIColor = UIColor.blue) {
        // 设置行间距
        let style = NSMutableParagraphStyle()
        // 间隙
        style.lineSpacing = 5
        let attDic = [NSAttributedString.Key.foregroundColor: self.textColor ?? UIColor.gray,
                      NSAttributedString.Key.font: self.font ?? UIFont.systemFont(ofSize: 16)
        ]
        
        let attString = NSMutableAttributedString(string: content, attributes: attDic as [NSAttributedString.Key : Any])
        for e in tapTexts.enumerated() {
            let nsRange = (attString.string as NSString).range(of: e.element)
            attString.addAttribute(NSAttributedString.Key.link, value: "\(e.offset)_\(tapUrls[e.offset])", range: nsRange)
        }
        
        let linkAttDic = [NSAttributedString.Key.foregroundColor : tapColor,
        ]
        
        linkTextAttributes = linkAttDic
        attributedText = attString
        isSelectable = true
        isEditable = false
    }
}
